var request = require('request');
var moment = require('moment');
var utils = require('./TUtils');
const { SSL_OP_SSLEAY_080_CLIENT_DH_BUG } = require('constants');

class TInputDatas {
    constructor() {
            this.config = {
                srcUrls: {
                    real: "http://123.234.35.141:1008/ashx/dataManage/HCInterface.ashx?action=getNewData&datatype=minute",
                    his: "http://123.234.35.141:1008/ashx/dataManage/HCInterface.ashx?action=getHistoryData&datatype={dateType}&startDate={start}&endDate={end}&mn={mn}",
                    devices: "http://123.234.35.141:1008/ashx/dataManage/HCInterface.ashx?action=getAllDevices"
                },
                db: {
                    dbUrl: "http://192.168.1.15:8086",
                    dbName: "gangkou_sd"
                },
                fields: [
                    'co', 'so2', 'no2', 'o3', 'pm10', 'pm25', 'tsp', 'ta', 'ua', 'ws', 'wd'
                ],
                aqiFields: [
                    'co', 'so2', 'no2', 'o3', 'pm10', 'pm25'
                ]
            };
            this.mns = ["HC601020110091", "HC601021010001", "HC622421051076", "HC622421051077", "HC622421051078", "HC622421051079", "HC622421051080", "HC622421051081", "HC622421051082", "HC622421051083", "HC622421051084", "HC622421051085", "HC622421051086", "HC622421051087", "HC650621060001", "HC650621060002", "HC650621060004", "HC650621060005"];
            this.aqiDict = {
                "so2-24": {
                    "maxv": 2620,
                    "maxi": 500,
                    "items": [{
                            "il": 0,
                            "ih": 50,
                            "bpl": 0,
                            "bph": 50,
                        },
                        {
                            "il": 50,
                            "ih": 100,
                            "bpl": 50,
                            "bph": 150,
                        },
                        {
                            "il": 100,
                            "ih": 150,
                            "bpl": 150,
                            "bph": 475,
                        },
                        {
                            "il": 150,
                            "ih": 200,
                            "bpl": 475,
                            "bph": 800,
                        },
                        {
                            "il": 200,
                            "ih": 300,
                            "bpl": 800,
                            "bph": 1600,
                        },
                        {
                            "il": 300,
                            "ih": 400,
                            "bpl": 1600,
                            "bph": 2100,
                        },
                        {
                            "il": 400,
                            "ih": 500,
                            "bpl": 2100,
                            "bph": 2620,
                        },
                    ]
                },
                "so2-1": {
                    "maxv": 800,
                    "maxi": 500,
                    "items": [{
                            "il": 0,
                            "ih": 50,
                            "bpl": 0,
                            "bph": 150,
                        },
                        {
                            "il": 50,
                            "ih": 100,
                            "bpl": 150,
                            "bph": 500,
                        },
                        {
                            "il": 100,
                            "ih": 150,
                            "bpl": 500,
                            "bph": 650,
                        },
                        {
                            "il": 150,
                            "ih": 200,
                            "bpl": 650,
                            "bph": 800,
                        },
                    ],
                },
                "no2-24": {
                    "maxv": 940,
                    "maxi": 500,
                    "items": [{
                            "il": 0,
                            "ih": 50,
                            "bpl": 0,
                            "bph": 40,
                        },
                        {
                            "il": 50,
                            "ih": 100,
                            "bpl": 40,
                            "bph": 80,
                        },
                        {
                            "il": 100,
                            "ih": 150,
                            "bpl": 80,
                            "bph": 180,
                        },
                        {
                            "il": 150,
                            "ih": 200,
                            "bpl": 180,
                            "bph": 280,
                        },
                        {
                            "il": 200,
                            "ih": 300,
                            "bpl": 280,
                            "bph": 565,
                        },
                        {
                            "il": 300,
                            "ih": 400,
                            "bpl": 565,
                            "bph": 750,
                        },
                        {
                            "il": 400,
                            "ih": 500,
                            "bpl": 750,
                            "bph": 940,
                        },
                    ]
                },
                "no2-1": {
                    "maxv": 3840,
                    "maxi": 500,
                    "items": [{
                            "il": 0,
                            "ih": 50,
                            "bpl": 0,
                            "bph": 100,
                        },
                        {
                            "il": 50,
                            "ih": 100,
                            "bpl": 100,
                            "bph": 200,
                        },
                        {
                            "il": 100,
                            "ih": 150,
                            "bpl": 200,
                            "bph": 700,
                        },
                        {
                            "il": 150,
                            "ih": 200,
                            "bpl": 700,
                            "bph": 1200,
                        },
                        {
                            "il": 200,
                            "ih": 300,
                            "bpl": 1200,
                            "bph": 2340,
                        },
                        {
                            "il": 300,
                            "ih": 400,
                            "bpl": 2340,
                            "bph": 3090,
                        },
                        {
                            "il": 400,
                            "ih": 500,
                            "bpl": 3090,
                            "bph": 3840,
                        },
                    ]
                },
                "pm10-24": {
                    "maxv": 600,
                    "maxi": 500,
                    "items": [{
                            "il": 0,
                            "ih": 50,
                            "bpl": 0,
                            "bph": 50,
                        },
                        {
                            "il": 50,
                            "ih": 100,
                            "bpl": 50,
                            "bph": 150,
                        },
                        {
                            "il": 100,
                            "ih": 150,
                            "bpl": 150,
                            "bph": 250,
                        },
                        {
                            "il": 150,
                            "ih": 200,
                            "bpl": 250,
                            "bph": 350,
                        },
                        {
                            "il": 200,
                            "ih": 300,
                            "bpl": 350,
                            "bph": 420,
                        },
                        {
                            "il": 300,
                            "ih": 400,
                            "bpl": 420,
                            "bph": 500,
                        },
                        {
                            "il": 400,
                            "ih": 500,
                            "bpl": 500,
                            "bph": 600,
                        },
                    ]
                },
                "pm25-24": {
                    "maxv": 500,
                    "maxi": 500,
                    "items": [{
                            "il": 0,
                            "ih": 50,
                            "bpl": 0,
                            "bph": 35,
                        },
                        {
                            "il": 50,
                            "ih": 100,
                            "bpl": 35,
                            "bph": 75,
                        },
                        {
                            "il": 100,
                            "ih": 150,
                            "bpl": 75,
                            "bph": 115,
                        },
                        {
                            "il": 150,
                            "ih": 200,
                            "bpl": 115,
                            "bph": 150,
                        },
                        {
                            "il": 200,
                            "ih": 300,
                            "bpl": 150,
                            "bph": 250,
                        },
                        {
                            "il": 300,
                            "ih": 400,
                            "bpl": 250,
                            "bph": 350,
                        },
                        {
                            "il": 400,
                            "ih": 500,
                            "bpl": 350,
                            "bph": 500,
                        },
                    ]
                },
                "co-24": {
                    "maxv": 60,
                    "maxi": 500,
                    "items": [{
                            "il": 0,
                            "ih": 50,
                            "bpl": 0,
                            "bph": 2,
                        },
                        {
                            "il": 50,
                            "ih": 100,
                            "bpl": 2,
                            "bph": 4,
                        },
                        {
                            "il": 100,
                            "ih": 150,
                            "bpl": 4,
                            "bph": 14,
                        },
                        {
                            "il": 150,
                            "ih": 200,
                            "bpl": 14,
                            "bph": 24,
                        },
                        {
                            "il": 200,
                            "ih": 300,
                            "bpl": 24,
                            "bph": 36,
                        },
                        {
                            "il": 300,
                            "ih": 400,
                            "bpl": 36,
                            "bph": 48,
                        },
                        {
                            "il": 400,
                            "ih": 500,
                            "bpl": 48,
                            "bph": 60,
                        },
                    ]
                },
                "co-1": {
                    "maxv": 150,
                    "maxi": 500,
                    "items": [{
                            "il": 0,
                            "ih": 50,
                            "bpl": 0,
                            "bph": 5,
                        },
                        {
                            "il": 50,
                            "ih": 100,
                            "bpl": 5,
                            "bph": 10,
                        },
                        {
                            "il": 100,
                            "ih": 150,
                            "bpl": 10,
                            "bph": 35,
                        },
                        {
                            "il": 150,
                            "ih": 200,
                            "bpl": 35,
                            "bph": 60,
                        },
                        {
                            "il": 200,
                            "ih": 300,
                            "bpl": 60,
                            "bph": 90,
                        },
                        {
                            "il": 300,
                            "ih": 400,
                            "bpl": 90,
                            "bph": 120,
                        },
                        {
                            "il": 400,
                            "ih": 500,
                            "bpl": 120,
                            "bph": 150,
                        },
                    ]
                },
                "o3-1": {
                    "maxv": 1200,
                    "maxi": 500,
                    "items": [{
                            "il": 0,
                            "ih": 50,
                            "bpl": 0,
                            "bph": 160,
                        },
                        {
                            "il": 50,
                            "ih": 100,
                            "bpl": 160,
                            "bph": 200,
                        },
                        {
                            "il": 100,
                            "ih": 150,
                            "bpl": 200,
                            "bph": 300,
                        },
                        {
                            "il": 150,
                            "ih": 200,
                            "bpl": 300,
                            "bph": 400,
                        },
                        {
                            "il": 200,
                            "ih": 300,
                            "bpl": 400,
                            "bph": 800,
                        },
                        {
                            "il": 300,
                            "ih": 400,
                            "bpl": 800,
                            "bph": 1000,
                        },
                        {
                            "il": 400,
                            "ih": 500,
                            "bpl": 1000,
                            "bph": 1200,
                        },
                    ]
                },
                "o38-24": {
                    "maxv": 800,
                    "maxi": 500,
                    "items": [{
                            "il": 0,
                            "ih": 50,
                            "bpl": 0,
                            "bph": 100,
                        },
                        {
                            "il": 50,
                            "ih": 100,
                            "bpl": 100,
                            "bph": 160,
                        },
                        {
                            "il": 100,
                            "ih": 150,
                            "bpl": 160,
                            "bph": 215,
                        },
                        {
                            "il": 150,
                            "ih": 200,
                            "bpl": 215,
                            "bph": 265,
                        },
                        {
                            "il": 200,
                            "ih": 300,
                            "bpl": 265,
                            "bph": 800,
                        },
                    ]
                },
            }
        }
        //获取实时数据
    getRealDatas() {
            var me = this;
            return new Promise((success, faild) => {
                var dataItems = [];
                try {
                    var datas = {}
                    utils.TUtils.httpCall(me.config.srcUrls.real, "GET", null, null).then(res => {
                        try {
                            var items = JSON.parse(res.result);
                            if (items.Result) {
                                items.realDatas.forEach(item => {
                                    var key = item.mn + "." + item.time;
                                    var dataItem = datas[key];
                                    if (!dataItem) {
                                        dataItem = {
                                            key: key,
                                            mn: item.mn,
                                            time: item.time,
                                            fields: {}
                                        };
                                        datas[key] = dataItem;
                                    }
                                    me.config.fields.forEach(f => {
                                        var v = item[f];
                                        if (v && v > 0) {
                                            dataItem.fields[f] = v * 1.0;
                                        }
                                    })
                                });
                                dataItems = Object.values(datas);
                            }
                        } catch (er) {
                            console.log(er);
                        }
                        success(dataItems);
                    })
                } catch (eer) {
                    console.log(eer);
                    success(dataItems);
                }
            });
        }
        //获取历史数据
    getHisDatas(mn, dateType, start, end) {
            var me = this;
            return new Promise((success, faild) => {
                var dataItems = [];
                try {
                    var datas = {}
                    var hisUrl = me.config.srcUrls.his;
                    hisUrl = hisUrl.replace("{mn}", mn);
                    hisUrl = hisUrl.replace("{dateType}", dateType);
                    hisUrl = hisUrl.replace("{start}", start);
                    hisUrl = hisUrl.replace("{end}", end);
                    utils.TUtils.httpCall(hisUrl, "GET", null, null).then(res => {
                        try {
                            var items = JSON.parse(res.result);
                            if (items.Result) {
                                items.realDatas.forEach(item => {
                                    item.mn = mn;
                                    var key = item.mn + "." + item.time;
                                    var dataItem = datas[key];
                                    if (!dataItem) {
                                        dataItem = {
                                            key: key,
                                            mn: item.mn,
                                            time: item.time,
                                            fields: {}
                                        };
                                        datas[key] = dataItem;
                                    }
                                    me.config.fields.forEach(f => {
                                        var v = item[f];
                                        if (v && v > 0) {
                                            dataItem.fields[f] = v * 1.0;
                                        }
                                    })
                                });
                                dataItems = Object.values(datas);
                            }
                        } catch (er) {
                            console.log(er);
                        }
                        success(dataItems);
                    })
                } catch (eer) {
                    console.log(eer);
                    success(dataItems);
                }
            });
        }
        //计算日均值
    setDayDatas(start, end) {
            var me = this;
            return new Promise((success, faild) => {
                var dataItems = [];
                try {
                    var sql = "select mean(co) as co , mean(so2) as so2 , mean(no2) as no2 , mean(o3) as o3 , mean(pm10) as pm10 , mean(pm25) as pm25, mean(tsp) as tsp , mean(ta) as ta , mean(ua) as ua , mean(ws) as ws, mean(wd) as wd into T_D  from T_H where time>='{start}' and time<'{end}' group by mn , mon , flag8 , time(1d)  fill(none)  tz('Asia/Shanghai')";
                    sql = sql.replace("{start}", start);
                    sql = sql.replace("{end}", end);
                    var url = me.config.db.dbUrl + "/query?db=" + me.config.db.dbName;
                    var ps = {
                        q: sql
                    }
                    utils.TUtils.httpCall(url, "POST", ps, null).then(res => {
                        console.log(res);
                        success();
                    });

                } catch (eer) {
                    console.log(eer);
                    success(dataItems);
                }
            });
        }
        //计算O3每小时之前8小时内的平均值
    setO3Hour(start, end) {
            var me = this;
            return new Promise((success, faild) => {
                var dataItems = [];
                try {
                    var sql = "select moving_average(o3,8) as o38   into T_H  from T_H where time>={start} and time<={end} group by mn ,mon, flag8   fill(none)   tz('Asia/Shanghai')";
                    var startTm = utils.TUtils.getTimestampe(start);
                    var endTm = utils.TUtils.getTimestampe(end);
                    sql = sql.replace("{start}", startTm);
                    sql = sql.replace("{end}", endTm);
                    var url = me.config.db.dbUrl + "/query?db=" + me.config.db.dbName;
                    var ps = {
                        q: sql
                    }
                    utils.TUtils.httpCall(url, "POST", ps, null).then(res => {
                        console.log(res);
                        success();
                    });
                } catch (eer) {
                    console.log(eer);
                    success(dataItems);
                }
            });
        }
        //计算O3每日8小时最大滑动平均值
    setO3Day(start, end) {
            var me = this;
            return new Promise((success, faild) => {
                var dataItems = [];
                try {
                    var sql = "select   max(o38) as o38 into T_D from T_H where flag8='1' and time>={start} and time<={end} group by mn,mon, flag8 , time(1d) fill(none)   tz('Asia/Shanghai')";
                    var startTm = utils.TUtils.getTimestampe(start);
                    var endTm = utils.TUtils.getTimestampe(end);
                    sql = sql.replace("{start}", startTm);
                    sql = sql.replace("{end}", endTm);
                    var url = me.config.db.dbUrl + "/query?db=" + me.config.db.dbName;
                    var ps = {
                        q: sql
                    }
                    utils.TUtils.httpCall(url, "POST", ps, null).then(res => {
                        console.log(res);
                        success();
                    });
                } catch (eer) {
                    console.log(eer);
                    success(dataItems);
                }
            });
        }
        //计算指标IQI值
    getIqiValue(timeType, key, value) {
            var me = this;
            var res = null;
            try {
                if (timeType == "h") {
                    var dict = me.aqiDict[key + "-1"];
                    if (dict) {
                        if (value >= dict.maxv) {
                            res = dict.maxi;
                        } else {
                            var currents = dict.items.filter(item => {
                                return item.bph > value && item.bpl <= value;
                            })
                            if (currents.length > 0) {
                                var item = currents[0];
                                res = (item.ih - item.il) * (value - item.bpl) * 1.0 / (item.bph - item.bpl) + item.bpl;
                            }
                        }
                    }
                } else if (timeType == "d") {
                    var dict = me.aqiDict[key + "-24"];
                    if (dict) {
                        if (value >= dict.maxv) {
                            res = dict.maxi;
                        } else {
                            var currents = dict.items.filter(item => {
                                return item.bph > value && item.bpl <= value;
                            })
                            if (currents.length > 0) {
                                var item = currents[0];
                                res = (item.ih - item.il) * (value - item.bpl) * 1.0 / (item.bph - item.bpl) + item.bpl;
                            }
                        }
                    }
                }
            } catch (er) {
                console.log(er);
            }
            return res;
        }
        //计算1小时的IQI
    setIqi1H(start, end) {
            var me = this;
            return new Promise((success, faild) => {
                var dataItems = [];
                try {
                    var sql = "select  * from T_H where time>='{start}' and time<='{end}'  tz('Asia/Shanghai')";
                    sql = sql.replace("{start}", start);
                    sql = sql.replace("{end}", end);
                    var url = me.config.db.dbUrl + "/query?db=" + me.config.db.dbName;
                    var ps = {
                        q: sql
                    }
                    utils.TUtils.httpCall(url, "GET", ps, null).then(res => {
                        console.log(res);
                        try {
                            var resData = JSON.parse(res.result).results[0].series[0];
                            var cols = resData.columns;
                            var rows = resData.values;
                            var datas = [];
                            rows.forEach(r => {
                                var tags = {};
                                var time = "";
                                var item = {};
                                for (var i = 0; i < cols.length; i++) {
                                    var c = cols[i];
                                    if (c == "mn" || c == "mon" || c == "flag8") {
                                        tags[c] = r[i];
                                    } else if (c == "time") {
                                        time = r[i];
                                    } else if (c == "so2" || c == "no2" || c == "co" || c == "o3") {
                                        var v = r[i];
                                        if (v != null && v > 0) {
                                            var iqiValue = me.getIqiValue('h', c, v);
                                            item[c + '_iqi'] = iqiValue;
                                        }
                                    }
                                }
                                if (Object.keys(item).length > 0) {
                                    datas.push({
                                        timestampe: utils.TUtils.getTimestampe(time),
                                        tags: tags,
                                        fields: item
                                    })
                                }
                            })
                            console.log(datas);
                            utils.TUtils.writeDBBatch(
                                me.config.db.dbUrl, me.config.db.dbName, "T_H", datas).then(_ => {
                                success(datas);
                            });

                        } catch (eer) {
                            console.log(eer);
                            success();
                        }
                    });

                    var setItem = function() {

                    }
                } catch (eer) {
                    console.log(eer);
                    success(dataItems);
                }
            });
        }
        //计算1天的IQI
    setIqi1Day(start, end) {
            var me = this;
            return new Promise((success, faild) => {
                var dataItems = [];
                try {
                    var sql = "select  * from T_D where time>='{start}' and time<='{end}'  tz('Asia/Shanghai')";
                    sql = sql.replace("{start}", start);
                    sql = sql.replace("{end}", end);
                    var url = me.config.db.dbUrl + "/query?db=" + me.config.db.dbName;
                    var ps = {
                        q: sql
                    }
                    utils.TUtils.httpCall(url, "GET", ps, null).then(res => {
                        console.log(res);
                        try {
                            var resData = JSON.parse(res.result).results[0].series[0];
                            var cols = resData.columns;
                            var rows = resData.values;
                            var datas = [];
                            rows.forEach(r => {
                                var tags = {};
                                var time = "";
                                var item = {};
                                for (var i = 0; i < cols.length; i++) {
                                    var c = cols[i];
                                    if (c == "mn" || c == "mon" || c == "flag8") {
                                        tags[c] = r[i];
                                    } else if (c == "time") {
                                        time = r[i];
                                    } else if (c == "so2" || c == "no2" || c == "co" || c == "o38" || c == "pm25" || c == "pm10") {
                                        var v = r[i];
                                        if (v != null && v > 0) {
                                            var iqiValue = me.getIqiValue('d', c, v);
                                            if (c == "o38") {
                                                item.o3_iqi = iqiValue;
                                            } else {
                                                item[c + '_iqi'] = iqiValue;
                                            }
                                        }
                                    }
                                }
                                if (Object.keys(item).length > 0) {
                                    datas.push({
                                        timestampe: utils.TUtils.getTimestampe(time),
                                        tags: tags,
                                        fields: item
                                    })
                                }
                            })
                            console.log(datas);
                            utils.TUtils.writeDBBatch(
                                me.config.db.dbUrl, me.config.db.dbName, "T_D", datas).then(_ => {
                                success(datas);
                            });

                        } catch (eer) {
                            console.log(eer);
                            success();
                        }
                    });

                    var setItem = function() {

                    }
                } catch (eer) {
                    console.log(eer);
                    success(dataItems);
                }
            });
        }
        //计算1天的IQI
    getAqi(dataItem) {
            var me = this;
            var res = {
                aqi: 0,
                aqiField: ""
            }
            try {
                me.config.aqiFields.forEach(f => {
                    var key = f + "_iqi";
                    var v = dataItem[key];
                    var flag = v && v != null && v > res.aqi;
                    if (flag) {
                        res.aqi = v;
                        res.aqiField = f;
                    }
                })
            } catch (eer) {
                console.log(eer);
            }
            res.aqi = res.aqi > 0 ? res.aqi : null;
            return res;
        }
        //计算周评价值
    setWeekDatas(start, end) {
            var me = this;
            return new Promise((success, faild) => {
                var dataItems = [];
                try {
                    var sql = "select mean(so2) as so2_w , PERCENTILE(so2,98) as so2_p ,  mean(no2) as no2_w , PERCENTILE(no2,98) as no2_p  ,  mean(tsp) as tsp_w , PERCENTILE(tsp,95) as tsp_p  ,  mean(pm10) as pm10_w , PERCENTILE(pm10,95) as pm10_p  ,  mean(pm25) as pm25_w , PERCENTILE(pm25,95) as pm25_p  ,  PERCENTILE(co,95) as co_p  ,  PERCENTILE(o38,90) as o3_p   from T_D where time>={start} and time<{end} group by mn , mon, flag8 , time(1w) fill(none)  tz('Asia/Shanghai')";
                    var startTm = utils.TUtils.getTimestampe(start);
                    var endTm = utils.TUtils.getTimestampe(end);
                    sql = sql.replace("{start}", startTm);
                    sql = sql.replace("{end}", endTm);
                    var url = me.config.db.dbUrl + "/query?db=" + me.config.db.dbName;
                    var ps = {
                        q: sql
                    }
                    utils.TUtils.httpCall(url, "POST", ps, null).then(res => {
                        console.log(res);
                        success();
                    });
                } catch (eer) {
                    console.log(eer);
                    success(dataItems);
                }
            });
        }
        //时段评价数据
    getMaxI(start, end) {
            var me = this;
            return new Promise((success, faild) => {
                try {
                    //获取时段内评价基础数据
                    var getMaxIDatas = function() {
                        var dataItems = {};
                        return new Promise((su, fa) => {
                            try {
                                var sql = "select mean(so2)/60.0 as so2_ia ,  PERCENTILE(so2,98)/50 as so2_id ,  mean(so2) as so2 , PERCENTILE(so2,98) as so2_p ,  mean(no2)/40.0 as no2_ia ,  PERCENTILE(no2,98)/40 as no2_id ,  mean(no2) as no2 , PERCENTILE(no2,98) as no2_p  ,   mean(pm10)/70.0 as pm10_ia ,  PERCENTILE(pm10,95)/50 as pm10_id ,  mean(pm10) as pm10 , PERCENTILE(pm10,95) as pm10_p  , mean(pm25)/35.0 as pm25_ia ,  PERCENTILE(pm25,95)/35 as pm25_id ,  mean(pm25) as pm25 , PERCENTILE(pm25,95) as pm25_p  ,  mean(co)/4.0 as co_ia ,  PERCENTILE(co,95)/2.0 as co_id ,  mean(co) as co , PERCENTILE(co,95) as co_p  ,  mean(o38)/160 as o3_ia ,  PERCENTILE(o38,90)/100 as o3_id ,  mean(o38) as o3 , PERCENTILE(o38,90) as o3_p  from T_D where time>={start} and time<{end} group by mn , mon fill(none)  tz('Asia/Shanghai')";
                                var startTm = utils.TUtils.getTimestampe(start);
                                var endTm = utils.TUtils.getTimestampe(end);
                                sql = sql.replace("{start}", startTm);
                                sql = sql.replace("{end}", endTm);
                                var url = me.config.db.dbUrl + "/query?db=" + me.config.db.dbName;
                                var ps = {
                                    q: sql
                                }
                                var keys = ['so2', 'no2', 'co', 'o3', 'pm10', 'pm25'];
                                utils.TUtils.httpCall(url, "POST", ps, null).then(res => {
                                    var sers = JSON.parse(res.result).results[0].series;
                                    sers.forEach(ser => {
                                        var mnItem = {
                                            mn: ser.tags.mn
                                        };
                                        dataItems[mnItem.mn] = mnItem;
                                        for (var i = 0; i < ser.columns.length; i++) {
                                            var c = ser.columns[i];
                                            var v = ser.values[0][i];
                                            mnItem[c] = v;
                                        }
                                        var sumValue = 0;
                                        keys.forEach(key => {
                                            var itemValue = getMaxItemvalue(mnItem, key);
                                            mnItem['maxI_' + key] = itemValue;
                                            sumValue += itemValue;
                                        });
                                        mnItem.maxIsum = sumValue;
                                    });
                                    su(dataItems);
                                });

                            } catch (eer) {
                                console.log(eer);
                                su(dataItems);
                            }
                        })
                    }
                    var getMaxItemvalue = function(dataItem, key) {
                        var res = 0;
                        try {
                            var k0 = key + "_ia";
                            var k1 = key + "_id";
                            var v0 = (dataItem[k0] && dataItem[k0] > 0) ? dataItem[k0] : 0;
                            var v1 = (dataItem[k1] && dataItem[k1] > 0) ? dataItem[k1] : 0;
                            res = v0 > v1 ? v0 : v1;
                            dataItem[key + "_i_Max"] = res;
                        } catch (eer) {
                            res = 0;
                        }
                        return res;
                    }
                    getMaxIDatas().then(resItems => {
                        console.log(resItems);
                        success(resItems);
                    })

                } catch (eer) {
                    console.log(eer);
                    success([]);
                }
            });
        }
        //时段评价数据
    getQueryResult(sql, sqlPs) {
            var me = this;
            return new Promise((success, faild) => {
                try {
                    var exeSql = sql;
                    Object.keys(sqlPs).forEach(p => {
                        exeSql = exeSql.replace("{" + p + "}", sqlPs[p]);
                    })
                    var url = me.config.db.dbUrl + "/query?db=" + me.config.db.dbName;
                    var ps = {
                        q: exeSql
                    }
                    utils.TUtils.httpCall(url, "GET", ps, null).then(res => {
                        var resDatas = [];
                        try {
                            var sers = JSON.parse(res.result).results[0].series;
                            sers.forEach(ser => {
                                for (var i = 0; i < ser.values.length; i++) {
                                    var row = ser.values[i];
                                    var item = {};
                                    for (var k = 0; k < ser.columns.length; k++) {
                                        var c = ser.columns[k];
                                        item[c] = row[k];
                                    }
                                    if (item.tags && item.tags.mn) {
                                        item.mn = item.tags.mn;
                                    }
                                    resDatas.push(item);
                                }
                            })
                        } catch (er1) {
                            console.log(er1);
                        }
                        success(resDatas);
                    });

                } catch (eer) {
                    console.log(eer);
                    success([]);
                }
            });
        }
        //获取设备列表
    getmns() {
            var me = this;
            return new Promise((success, faild) => {
                try {
                    var devices = {};
                    utils.TUtils.httpCall(me.config.srcUrls.devices, "GET", null, null).then(res => {
                        try {
                            var items = JSON.parse(res.result);
                            if (items.Result) {
                                items.realDatas.forEach(item => {
                                    devices[item.mnCode] = item;
                                });
                            }
                            me.mns = Object.keys(devices);
                        } catch (er) {
                            console.log(er);
                        }
                        success(me.mns);
                    })
                } catch (eer) {
                    console.log(eer);
                    success([]);
                }
            });
        }
        //写入DB
    saveSrc2Db(dataItems, tableName) {
        var me = this;
        return new Promise((success, faild) => {
            var items = [];
            try {
                items = JSON.parse(JSON.stringify(dataItems));
                var write2DB = function() {
                    if (items.length > 0) {
                        var item = items.shift();
                        var aDbUrl = me.config.db.dbUrl;
                        var dbName = me.config.db.dbName;
                        var fields = item.fields;
                        var tmHourStr = item.time.substr(11, 2);
                        var tmHour = parseInt(tmHourStr);
                        var flag8 = tmHour > 7 ? 1 : 0;
                        if (tableName == "T_D") {
                            flag8 = 1;
                        }
                        var tags = {
                            mn: item.mn,
                            mon: item.time.substr(0, 7),
                            flag8: flag8
                        };
                        var timestampe = utils.TUtils.getTimestampe(item.time);
                        utils.TUtils.writeDB(aDbUrl, dbName, tableName, tags, fields, timestampe).then(_ => {
                            write2DB();
                        })
                    } else {
                        success();
                    }
                }
                write2DB();
            } catch (eer) {
                console.log(eer);
                success(dataItems);
            }
        });
    }

    //导入一段时间的数据
    inputData(start, end) {
        var me = this;
        return new Promise((success, faild) => {
            try {
                var startH = start;
                var endH = end;
                me.getmns().then(mns => {
                    var inputItem = function() {
                        if (mns.length > 0) {
                            var mn = mns.shift();
                            me.getHisDatas(mn, 'hour', startH, endH).then(resHour => {
                                return me.saveSrc2Db(resHour, "T_H");
                            }).then(_ => {
                                inputItem();
                            })
                        } else {
                            me.setDayDatas(startH, endH).then(_ => {
                                return me.setO3Hour(startH, endH);
                            }).then(_ => {
                                return me.setO3Day(startH, endH);
                            }).then(_ => {
                                return me.setIqi1H(startH, endH);
                            }).then(_ => {
                                return me.setIqi1Day(startH, endH);
                            }).then(_ => {
                                return me.setWeekDatas(startH, endH);
                            }).then(_ => {
                                success();
                            })
                        }
                    }
                    inputItem();
                })

            } catch (eer) {
                console.log(eer);
                success();
            }
        });
    }
    inputDataEx() {
        var me = this;
        return new Promise((success, faild) => {
            try {
                var now = (new Date()).getTime();
                now += -1 * 24 * 3600 * 1000;
                var startH = moment(now).format('yyyy-MM-DD');
                now += 2 * 24 * 3600 * 1000;
                var endH = moment(now).format('yyyy-MM-DD');
                me.inputData(startH, endH).then(_ => {
                    success();
                })

            } catch (eer) {
                console.log(eer);
                success();
            }
        });
    }
    inputDataLoop() {
        var me = this;
        try {
            me.inputDataEx().then(_ => {
                setTimeout(() => {
                    me.inputDataLoop();
                }, 5 * 60 * 1000);
            })

        } catch (eer) {
            console.log(eer);
        }
    }
}

module.exports = {
        TInputDatas: TInputDatas
    }
    /*
var inputData = new TInputDatas();
inputData.getMaxI('2021-07-01', '2021-08-01').then(res => {
        console.log(res)
    })
    inputData.inputDataEx().then(_ => {
        console.log('in')
    })
    inputData.getRealDatas().then(res => {
        console.log(res);
        var ds = {};
        res.forEach(r => {
            ds[r.mn] = r;
        })
        var mns = Object.keys(ds);
        console.log(JSON.stringify(mns));
    });
    */